<template>
  <div class="q-mx-md q-mt-sm text-bold bg-white">当前项目：{{project.cname}}</div>
  <div class="my_page_container">
    <div class="bg-white">
      <AmyQueryItem
        search-label="变量名称"
        @make-search-operator="queryTable"
      />
    </div>
    <div class="bg-white">
      <q-scroll-area class="my-scroll-area-table">
        <q-table
          id="my-xls"
          bordered
          flat
          separator="cell"
          :tableTitle= "tableTitle"
          :columns="columns"
          row-key="name"
          :rows="dbFilterList"
          :pagination="dbPagination"
          :rows-per-page-options="[10,20]"
          selection="multiple"
          v-model:selected="selectedItems"
        >

          <!--  插槽：表格头部左侧    -->
          <template v-slot:top-left>
            <q-input outlined dense color="base" v-model="filterText" :input-style="{ width: '150px'}">
              <template v-slot:append>
                <q-icon name="search" color="indigo"/>
              </template>
            </q-input>
          </template>

          <!--  插槽：表格头部左侧    -->
          <template v-slot:top-right>
            <div class="q-gutter-sm">
              <q-btn
                dense
                unelevated
                color="secondary"
                label="新增"
                icon="mdi-comment-plus"
                @click="addDlgItem"
              />
              <q-btn
                dense
                unelevated
                color="amber"
                label="导入"
                icon="mdi-file-import"
              />
              <q-btn
                dense
                unelevated
                color="pink"
                label="导出"
                icon="mdi-database-export"
                @click="exportExcel"
              />
            </div>
          </template>

          <!--  插槽：某个单元格    -->
          <template #body-cell-deviceId="props">
            <q-td :props="props">
              {{findCatalogLabel(scaDeviceList, props.row.deviceId)}}
            </q-td>
          </template>
          <template #body-cell-ioTypeId="props">
            <q-td :props="props">
              {{findCatalogLabel(varTypeList, props.row.ioTypeId)}}
            </q-td>
          </template>
          <template #body-cell-operation="props">
            <q-td :props="props">
              <q-btn
                flat
                round
                dense
                color="primary"
                icon="edit"
                @click="editDlgItem(props.rowIndex)">
                <q-tooltip>编辑</q-tooltip>
              </q-btn>
              <q-btn
                flat
                round
                dense
                color="negative"
                icon="mdi-delete-empty"
                @click="deleteDlgItem(props.rowIndex)">
                <q-tooltip>删除</q-tooltip>
              </q-btn>
            </q-td>
          </template>
          <!--   底部插槽     -->
          <template v-slot:bottom>
            <AmyPagination :page-msg="dbPagination" @update="refreshTableAry"/>
          </template>
        </q-table>
      </q-scroll-area>
    </div>
    <div>
      <VariableDlg
        ref="myAddDlgRef"
        :item-data="getActiveItem()"
        :var-type-arr="varTypeList"
        :project-arr="scaProjectList"
        :device-arr="scaDeviceList"
        :var-unit-arr="unitTypeList"
        :formula-arr="formulaTypeList"
        :operation-arr="operationTypeList"
        @cancel-variable-item="cancelAddDlg"
        @submit-variable-item="submitAddDlg"
      />
      <AmyDeleteDlg
        ref="myDelDlgRef"
        :selected-index="deletedIndex"
        @btnSubmit="submitDelDlg"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { defineAsyncComponent, defineComponent, onMounted, onUnmounted, reactive, ref, watch, computed } from 'vue';
import api from 'axios';
import * as XLSX from 'xlsx';
import { useMessageNotify } from 'src/hook/common/useMessageNotify';
import BaseItem from 'pages/BaseItem.vue';
import { EStatusType, ItemType } from 'src/hook/common/useCommonVisitType';
import useCommonVisitDatabase from 'src/hook/common/useCommonVisitDatabase';
import { useCatalogTool } from 'src/hook/common/useCatalogTool';
import { CQueryParam } from 'src/components/basic/basicModel';

import { useRoute } from 'vue-router';
import { scaBaseUrlAPI, scaCatalogType } from 'src/util/ScaBaseConst';
import { hmiCatalogType } from 'src/util/HmiBaseConst';
import { useHmiCatalogTbl } from 'src/hook/useHmiCatalogTbl';
import { useScaCatalogTbl } from 'src/hook/useScaCatalogTbl';
import { DeviceItem } from 'pages/sca/device/DeviceModel';
import { useEditorStore } from 'stores/editorStore';
import { storeToRefs } from 'pinia';

const AmyListItem = defineAsyncComponent(() => import('components/basic/AmyListItem.vue'));
const AmyDeleteDlg = defineAsyncComponent(() => import('components/basic/AmyDeleteDlg.vue'));
const VariableDlg = defineAsyncComponent(() => import('./VariableDlg.vue'));
export type DeleteDlgInstance = InstanceType<typeof AmyDeleteDlg>;
export type DeviceDlgInstance = InstanceType<typeof VariableDlg>;


export default defineComponent({
  name: 'VariableIndex',
  extends: BaseItem,
  components: {
    AmyListItem,
    VariableDlg
  },
  setup (props, context) {
    //*********************************************************************************************
    //      路由
    //*********************************************************************************************
    //router是全局路由对象，route是当前路由对象
    let route = useRoute();
    let store = useEditorStore();
    const {
      project
    } = storeToRefs(store);
    //*********************************************************************************************
    //      消息通知
    //*********************************************************************************************
    //消息通知
    const {
      showMessage
    } = useMessageNotify();

    //*********************************************************************************************
    //      查询模块
    //*********************************************************************************************
    //查询输入参数
    let queryParam = reactive({
      id: 0,
      name: '',
      startDate: '',
      endDate: ''
    });

    //有条件查询
    const queryTable = (s: CQueryParam) => {
      queryParam.name = s.name;
      queryParam.startDate = s.startDate;
      queryParam.endDate = s.endDate;

      //有条件查询
      loadList();
    };

    //*********************************************************************************************
    //      读取表格数据
    //*********************************************************************************************
    //检索响应数据
    const state = reactive({
      itemData: {
        id: 0,
        cname: '',
        projectId: 0,
        deviceId: 0,
        ioAddr: 0,
        ioTypeId: 0,
        ioUnitId: 0,
        ioMin: 0,
        ioMax: 0,
        alarmMin: 0,
        alarmMax: 0,
        formulaId: 0,
        operationId: 0,
        isAlarm: false,
        isStore: false,
        collectPeriod: 0,
        storePeriod: 0,
        sortCode: '',
        description: '',
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      }
    });


    //查询数据库
    const fetchApi = () => {
      return api.post(scaBaseUrlAPI.SCA_VARIABLE_API_PAGE, {
        projectId: queryParam.id,
        name: queryParam.name,
        startDate: queryParam.startDate,
        endDate: queryParam.endDate,
        pageNum: dbPagination.value.pageNum,
        pageSize: dbPagination.value.pageSize
      });
    };

    //删除记录
    const deleteApi = (item: ItemType) => {
      return api.post(scaBaseUrlAPI.SCA_VARIABLE_API_DELETE, { id: item.id });
    };

    //增加记录
    const confirmAddApi = (item: ItemType) => {
      return api.post(scaBaseUrlAPI.SCA_VARIABLE_API_ADD, {
        id: item.id,
        cname: item.cname,
        projectId: item.projectId,
        deviceId: item.deviceId,
        ioAddr: item.ioAddr,
        ioTypeId: item.ioTypeId,
        ioUnitId: item.ioUnitId,
        ioMin: item.ioMin,
        ioMax: item.ioMax,
        alarmMin: item.alarmMin,
        alarmMax: item.alarmMax,
        formulaId: item.formulaId,
        operationId: item.operationId,
        isAlarm: item.isAlarm,
        isStore: item.isStore,
        collectPeriod: item.collectPeriod,
        storePeriod: item.storePeriod,
        sortCode: item.sortCode,
        description: item.description,
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      });
    };

    //修改记录
    const confirmEditApi = (item: ItemType) => {
      return api.post(scaBaseUrlAPI.SCA_VARIABLE_API_UPDATE, {
        id: item.id,
        cname: item.cname,
        projectId: item.projectId,
        deviceId: item.deviceId,
        ioAddr: item.ioAddr,
        ioTypeId: item.ioTypeId,
        ioUnitId: item.ioUnitId,
        ioMin: item.ioMin,
        ioMax: item.ioMax,
        alarmMin: item.alarmMin,
        alarmMax: item.alarmMax,
        formulaId: item.formulaId,
        operationId: item.operationId,
        isAlarm: item.isAlarm,
        isStore: item.isStore,
        collectPeriod: item.collectPeriod,
        storePeriod: item.storePeriod,
        sortCode: item.sortCode,
        description: item.description,
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      });
    };


    const {
      dbList,
      dbFilterList,
      dbPagination,
      dbCurrentIndex,
      dbStatus,
      getActiveItem,
      getItem,
      filterList,
      loadList,
      addItem,
      editItem,
      deleteItem,
      cancelItem,
      confirmApi
    } = useCommonVisitDatabase(state.itemData, fetchApi, confirmAddApi, confirmEditApi, deleteApi);

    //*********************************************************************************************
    //      读取目录
    //*********************************************************************************************
    const {
      findCatalogLabel,
      findCatalogId
    } = useCatalogTool();

    const {
      varTypeList,
      unitTypeList,
      formulaTypeList,
      operationTypeList,
      getHmiCatalog,
      removeHmiCatalog
    } = useHmiCatalogTbl();

    const {
      scaProjectList,
      scaDeviceList,
      scaVariableList,
      getScaCatalog,
      removeScaCatalog
    } = useScaCatalogTbl();

    //*********************************************************************************************
    //      表格
    //*********************************************************************************************
    const columns = [
      {
        name: 'id',
        required: true,
        label: 'ID',
        align: 'center',
        field: (row:any) => (row.id),
        sortable: true
      },
      { name: 'cname', align: 'center', label: '变量名称', field: 'cname' },
      { name: 'deviceId', align: 'center', label: '设备', field: 'deviceId' },
      { name: 'ioTypeId', align: 'center', label: '变量类型', field: 'ioTypeId' },
      { name: 'ioAddr', align: 'center', label: '变量地址', field: 'ioAddr' },
      { name: 'sortCode', align: 'center', label: '序码', field: 'sortCode' },
      { name: 'operation', align: 'center', label: '操作', field: 'operation' }
    ];

    let tableTitle = ref('用户数据');
    let selectedItems = ref([]);
    let filterText = ref('');
    let myDelDlgRef = ref<DeleteDlgInstance|null>(null);
    let myAddDlgRef = ref<DeviceDlgInstance|null>(null);
    let deletedIndex = ref(0);

    //检索显示
    const searchTableAry = () => {
      filterList(filterText.value);
    }

    //添加用户
    const addDlgItem = () => {
      if (myAddDlgRef.value) {
        addItem();
        myAddDlgRef.value.show('新建变量信息');
      }
    }

    //编辑用户
    const editDlgItem = (row: number) => {
      if (myAddDlgRef.value) {
        editItem(row);
        myAddDlgRef.value.show('编辑变量信息');
      }
    }

    //删除用户
    const deleteDlgItem = (row: number) => {
      if (myDelDlgRef.value) {
        deletedIndex.value = row;
        myDelDlgRef.value.show('变量信息');
      }
    }

    //更新分页组件
    const refreshTableAry = (pageNum: number) => {
      dbPagination.value.pageNum = pageNum;
      loadList();
    }

    //导出excel
    const exportExcel = () => {
      let workbook = XLSX.utils.table_to_book(document.getElementById('my-xls')); //需要在table上定义一个id
      try {
        XLSX.writeFile(workbook, 'BOX信息.xlsx');
      } catch (e) {
        showMessage('导出失败,失败信息:!');
      }
    }

    //保存
    const saveItem = (row: number) => {
      let item = getItem(row);
      if (item !== null) {
        confirmApi(item);
      }
    }

    //*********************************************************************************************
    //      增加、修改模块
    //*********************************************************************************************
    //取消添加
    const cancelAddDlg = () => {
      //判断是增加还是修改
      if (dbStatus.value === EStatusType.ADD_TYPE) {
        cancelItem(0);
      }
    }

    //新建提交
    const submitAddDlg = (item: DeviceItem) => {
      console.log(item);
      confirmApi(item);
      loadList();
    }

    //*********************************************************************************************
    //      删除确认模块
    //*********************************************************************************************
    //提交确认对话框
    const submitDelDlg = (index: number) => {
      deleteItem(index);
    }

    //*********************************************************************************************
    //      启动模块
    //*********************************************************************************************
    //初始化
    const init = () => {
      //表格数据,无条件检索
      if (route.query.id) {
        let id = parseInt(route.query.id as any);
        let name = route.query.name as string;
        if (!isNaN(id)) {
          queryParam.id = id;
          store.setProject(id, name);
        }
      }

      //加载数据
      loadList();

      //读取目录
      getHmiCatalog(hmiCatalogType.VAR_TYPE_CODE);
      getHmiCatalog(hmiCatalogType.UINT_TYPE_CODE);
      getHmiCatalog(hmiCatalogType.FORMULA_TPE_CODE);
      getHmiCatalog(hmiCatalogType.OPERATION_TYPE_CODE);
      getScaCatalog(scaCatalogType.PROJECT_CODE);
      getScaCatalog(scaCatalogType.DEVICE_CODE);
    }

    //监视检索框
    watch(filterText, () => {
      searchTableAry();
    });


    //挂载数据
    onMounted(() => {
      init();
    });

    //销毁数据
    onUnmounted(() => {
      removeHmiCatalog(hmiCatalogType.VAR_TYPE_CODE);
      removeHmiCatalog(hmiCatalogType.UINT_TYPE_CODE);
      removeHmiCatalog(hmiCatalogType.FORMULA_TPE_CODE);
      removeHmiCatalog(hmiCatalogType.OPERATION_TYPE_CODE);

      removeScaCatalog(scaCatalogType.PROJECT_CODE);
      removeScaCatalog(scaCatalogType.DEVICE_CODE);
    });

    return {
      project,
      queryTable,

      varTypeList,
      unitTypeList,
      formulaTypeList,
      operationTypeList,

      scaProjectList,
      scaDeviceList,
      scaVariableList,
      findCatalogLabel,
      findCatalogId,

      columns,
      tableTitle,
      selectedItems,
      filterText,
      deletedIndex,
      myDelDlgRef,
      myAddDlgRef,
      searchTableAry,
      addDlgItem,
      editDlgItem,
      deleteDlgItem,
      refreshTableAry,
      saveItem,

      dbList,
      dbFilterList,
      dbPagination,
      dbCurrentIndex,
      getActiveItem,

      cancelAddDlg,
      submitAddDlg,
      submitDelDlg,

      exportExcel
    }
  }
})

</script>

<style lang="scss" scoped>
.my_input {
  width: 150px;
}
</style>
